<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>刮刮乐1</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      .demo {
        position: relative;
      }
      .demo .text {
        position: absolute;
        left: 0;
        top: 0;
        z-index: -1;
        width: 400px;
        height: 100px;
        text-align: center;
        line-height: 100px;
        font-size: 20px;
      }
    </style>
  </head>
  <body>
    <div class="demo">
      <canvas id="canvas" width="400" height="100">
        您的浏览器不支持canvas,请更换浏览器!
      </canvas>
      <div class="text">恭喜你获得一亿元</div>
      <br />
      <button class="btn">再来一次</button>
    </div>
    <script>
      function loadImage(url) {
        return new Promise((resolve, reject) => {
          const img = new Image();
          img.setAttribute("crossOrigin", "anonymous");
          img.src = url;
          img.onload = () => {
            // 当图像加载完成后进行resolve
            resolve(img);
          };
          img.onerror = () => {
            reject(new Error("图像加载失败"));
          };
        });
      }
      window.onload = async function () {
        if (canvas.getContext) {
          const canvas = document.getElementById("canvas");
          const btn = document.getElementsByClassName("btn")[0];
          const ctx = canvas.getContext("2d");
          var image1 = await loadImage("./3.jpeg");
          let ptrn = ctx.createPattern(image1, "repeat");
          var image2 = await loadImage("./4.jpeg");
          let ptrn2 = ctx.createPattern(image2, "repeat");

          init(ctx);
          btn.addEventListener("click", function () {
            init(ctx);
          });

          async function init(ctx) {
            // 清空图层
            ctx.globalCompositeOperation = "source-over"; // 如果不设置回默认,则新涂层会添加失败
            ctx.clearRect(0, 0, 400, 100);

            // 绘制涂层
            ctx.fillStyle = ptrn2;
            ctx.fillRect(0, 0, 400, 100);
            ctx.fill();

            // 绘制字体
            ctx.fillStyle = "#fc1";
            ctx.font = "26px sans-serif";
            ctx.textBaseline = "middle";
            ctx.textAlign = "center";
            ctx.fillText("刮刮乐", 200, 50);

            ctx.fillStyle = ptrn;
            /*
                  ctx.globalCompositeOperation = type 是画布上的全局合成操作，用于在绘制时指定新像素如何与已有的像素混合
                  "destination-out": 新绘制的内容会擦除掉已有内容，只留下未被覆盖的部分
                */
            ctx.globalCompositeOperation = "destination-out";

            // 当鼠标快速刮涂层时,会出现刮开的区域不连贯问题.记录两个点的坐标,采用lineTo的方式画线
            let prevPoint = null; // 上一个点的位置
            let curPoint = null; // 当前点的位置
            canvas.addEventListener("mousedown", (e) => {
              prevPoint = {
                x: e.offsetX,
                y: e.offsetY,
              };
              canvas.addEventListener("mousemove", clearFun);

              document.addEventListener("mouseup", () => {
                canvas.removeEventListener("mousemove", clearFun);
              });
            });

            function clearFun(e) {
              curPoint = {
                x: e.offsetX,
                y: e.offsetY,
              };

              ctx.lineWidth = 20;
              ctx.lineCap = "round";
              ctx.beginPath();
              ctx.moveTo(prevPoint.x, prevPoint.y);
              ctx.lineTo(curPoint.x, curPoint.y);
              
              ctx.stroke();
              ctx.fill();
              ctx.closePath();

              prevPoint = curPoint;
            }
          }
        }
      };
    </script>
  </body>
</html>
